package apoc.core.core.handler;

import apoc.core.plugin.tick.IScheduledTickHandler;
import apoc.core.plugin.tick.ITickHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;

//import apochud.gui.NewIngameGUI;

public class TickHandler
{

    private HashMap<TickEvent.Type, Long> ticks = new HashMap<TickEvent.Type, Long>();
    private ArrayList<ITickHandler> tickHandlers = new ArrayList<ITickHandler>();
    private ArrayList<IScheduledTickHandler> scheduledTickHandlers = new ArrayList<IScheduledTickHandler>();

    public void registerTickHandler(ITickHandler tickHandler)
    {
        tickHandlers.add(tickHandler);
    }

    public void registerScheduledTickHandler(IScheduledTickHandler tickHandler)
    {
        scheduledTickHandlers.add(tickHandler);
    }

    @SubscribeEvent
    public void tick(TickEvent event)
    {
        if (event.phase == TickEvent.Phase.START)
            if (ticks.get(event.type) == null)
            {
                ticks.put(event.type, 0L);
            } else
            {
                ticks.put(event.type, ticks.get(event.type) + 1);
            }
        ArrayList<Object> params = new ArrayList<Object>();
        switch (event.type)
        {
            case WORLD:
                params.add(((TickEvent.WorldTickEvent) event).world);
                break;
            case PLAYER:
                params.add(((TickEvent.PlayerTickEvent) event).player);
                break;
            case RENDER:
                params.add(((TickEvent.RenderTickEvent) event).renderTickTime);
                break;
            default:
                break;
        }
        for (ITickHandler tickHandler : tickHandlers)
        {
            if (tickHandler.side() == event.side)
                if (tickHandler.ticks() != null && tickHandler.ticks().contains(event.type))
                {
                    if (event.phase == TickEvent.Phase.START)
                        tickHandler.tickStart(EnumSet.of(event.type), params.toArray());
                    else
                        tickHandler.tickEnd(EnumSet.of(event.type), params.toArray());
                }
        }

        for (IScheduledTickHandler tickHandler : scheduledTickHandlers)
        {
            if (tickHandler.side() == event.side)
                if (tickHandler.ticks() != null && tickHandler.ticks().contains(event.type))
                {
                    if (ticks.get(event.type) % tickHandler.nextTickSpacing() == 0)
                    {
                        if (event.phase == TickEvent.Phase.START)
                            tickHandler.tickStart(EnumSet.of(event.type), params.toArray());
                        else
                            tickHandler.tickEnd(EnumSet.of(event.type), params.toArray());
                    }
                }
        }
    }
}